<template>
  <el-dialog title="预览" v-if="visiable" :visible.sync="visiable" @close="handleCloseDialog" destroy-on-close width="80%" append-to-body top="5vh">
    <div class="sail-header-dialog-content">
      <vue-office-docx :src="url" @rendered="rendered" v-if="['doc', 'docx'].includes(fileType)" class="view-height" />
      <pre class="pre-style" v-html="fileContent" v-else-if="['txt', 'text'].includes(fileType)" v-loading="txtLoading" element-loading-text="加载中，请稍后..."></pre>
      <vue-office-excel :src="url" @rendered="renderedHandler" @error="errorHandler" v-else class="view-height" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleCloseDialog">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
//引入VueOffice组件
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';

//引入相关样式
import '@vue-office/docx/lib/index.css';
//引入相关样式
import '@vue-office/excel/lib/index.css';
import { readerText } from '@/api/admin/downloadCenter';
export default {
  name: 'docPreview',
  components: {
    VueOfficeDocx,
    VueOfficeExcel
  },
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      default: ''
    },
    fileType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileContent: '',
      txtLoading: false
    };
  },
  watch: {
    visiable: {
      handler(val) {
        if (['txt', 'text'].includes(this.fileType)) {
          this.getPreviewFile(this.url);
        }
      },
      deep: true
    }
  },
  methods: {
    rendered() {
      console.log('渲染完成');
    },
    handleCloseDialog() {
      this.fileContent = '';
      this.$emit('update:visiable', false);
    },
    renderedHandler() {
      console.log('渲染完成');
    },
    errorHandler() {
      console.log('渲染失败');
    },
    async getPreviewFile(link) {
      let fileContent;
      try {
        this.txtLoading = true;
        const res = await readerText({ link: link });
        fileContent = res.data;
      } catch (e) {
        fileContent = '内容加载失败，请下载后查看';
        console.warn(e);
      } finally {
        this.txtLoading = false;
        this.fileContent = fileContent;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.view-height {
  min-height: 400px;
}
.pre-style {
  width: 100%;
  height: 400px;
}
</style>
